package com.bskj.kuaifu.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.bskj.common.bean.model.ParkingLotCustomer;
import com.bskj.common.bean.model.UserCar;
import com.bskj.common.bean.model.UserCoupon;
import com.bskj.common.bean.model.UserInfo;
import com.bskj.common.utils.EncryptUtil;
import com.bskj.common.utils.JSONUtil;
import com.bskj.common.utils.LogUtils;
import com.bskj.common.utils.ResultMapUtil;
import com.bskj.common.utils.StringUtils;
import com.bskj.common.web.BaseController;
import com.bskj.kuaifu.service.IParkingLotCustomerService;
import com.bskj.kuaifu.service.IUserCouponService;
import com.bskj.kuaifu.service.IUserInfoService;

/**
 * Created by mocaijin on 16/01/2018.
 */
@Controller
@RequestMapping("userCoupon")
public class UserCouponController extends BaseController {

    @Autowired
    private IParkingLotCustomerService parkingLotCustomerService;
    
    @Autowired
    private IUserInfoService userInfoService;


    @Autowired
    private IUserCouponService userCouponService;
    
    @RequestMapping("page/receiveCouponIndex")
    public ModelAndView receive(Integer userId,String openId, String appId, String jsonWechatUser, String userCouponEncryptStr) throws Exception {
    	JSONObject jsonUser=JSONUtil.getJSONFromString(jsonWechatUser);
    	UserInfo user=null;
    	String unionid=(String)jsonUser.get("unionid");
    	if(userId==null){
    		if(unionid == null){
    			user =userInfoService.getUserInfoByOpenId(openId);
    		}else {
    			user =userInfoService.getUserInfoByUnionidId(unionid);
			}
    	}else {
			user=userInfoService.get(userId);
		}
    	if(user==null){
    		UserInfo userInfo=new UserInfo();
        	userInfo.setName((String)jsonUser.get("nickname"));
        	userInfo.setImage((String)jsonUser.get("headimgurl"));
        	userInfo.setUnionid((String)jsonUser.get("unionid"));
        	userInfo.setAppId(appId);
        	userInfo.setOpenId(openId);
        	userInfo.setCreateTime(new Date());
        	userInfo.setUpdateTime(new Date());
        	userInfoService.insert(userInfo);
        	userId=userInfoService.getUserInfoByOpenId(openId).getId();
    	}else {
			userId=user.getId();
		}
    	ModelAndView mv = getRequestModelAndView();
    	
    	JSONObject generateCouponParams = new JSONObject();
        generateCouponParams.put("uri", "/userCoupon/page/receiveCoupon");
        generateCouponParams.put("userId", userId);
        generateCouponParams.put("subscribe",jsonUser.get("subscribe"));
        generateCouponParams.put("jsonWechatUser",jsonWechatUser);
        LogUtils.debug(jsonWechatUser+jsonUser.get("subscribe"));
        generateCouponParams.put("userCouponEncryptStr", userCouponEncryptStr);
        
        mv.addObject("generateCouponParams", EncryptUtil.encrypt(generateCouponParams.toJSONString()));
        
        List<UserCar> userCars = userInfoService.getMyCarNo(userId);
        if(userCars != null && userCars.size() > 0){
        	mv.setViewName("/user/myCarNo");
        	mv.addObject("userCars", userCars);
        	addMyCarNoParams(userId, mv);
        	mv.addObject("userCouponEncryptStr", userCouponEncryptStr);
        }else {
        	mv.setViewName("/user/addCarNo");
        	bindCarNoParams(userId, mv);
		}
        
        mv.addObject("userId", userId);
        return mv;
    }


    /**
     * 确认接收停车券
     *
     * @param userId
     * @param shopId
     * @return
     * @throws Exception
     */
    @RequestMapping("page/receiveCoupon")
    public ModelAndView receiveCouponIndex(Integer userId, String jsonWechatUser, String userCouponEncryptStr, String carNo) throws Exception {
        LogUtils.debug(JSONObject.toJSONString(getRequest().getParameterMap()));
        ModelAndView mv = new ModelAndView();
        UserCoupon userCoupon = UserCoupon.toBean(userCouponEncryptStr);
        
        //领取券
        Map<String,Object> resultMap = userCouponService.userReceiveCoupon(userCoupon, userId, carNo);
        
        if(StringUtils.isBank(carNo)){//车牌为空
        	mv.setViewName("/coupon/noCarNO");
        	return mv;
        }
        
        
        if((boolean)resultMap.get("result")) {
        	//券领取成功
        	JSONObject jsonUser=JSONUtil.getJSONFromString(jsonWechatUser);
            LogUtils.debug(jsonWechatUser+jsonUser.get("subscribe"));
            mv.addObject("subscribe", jsonUser.get("subscribe"));
            mv.setViewName("/coupon/receiveCoupon");
            
            Integer parkingLotCustomerId = userCoupon.getParkingLotCustomerId();
            ParkingLotCustomer parkingLotCustomer = parkingLotCustomerService.get(parkingLotCustomerId);
            mv.addObject("parkingPlaceName", parkingLotCustomer.getName());
            mv.addObject("userCoupon", userCoupon);

            JSONObject myCouponsParams = new JSONObject();
            myCouponsParams.put("uri", "/userCoupon/page/myCouponListIndex");
            myCouponsParams.put("userId", userId);
            mv.addObject("myCouponsParams", EncryptUtil.encrypt(myCouponsParams.toJSONString()));
        } else {
        	String errorCode = (String)resultMap.get("errorCode");
        	if("40001".equals(errorCode)) {
        		//券已经被领取完
        		mv.setViewName("/coupon/noCoupon");
            	return mv;
        	}
        	
        	if("40002".equals(errorCode)) {
        		//券已经过期
        		mv.setViewName("/coupon/pastCoupon");
            	return mv;
        	}
        }
        return mv;
    }

    @ResponseBody
    @RequestMapping("newShopCoupon")
    public Map<String, Object> newShopCoupon(Integer userId, String userCouponEncryptStr) {
        LogUtils.debug(JSONObject.toJSONString(getRequest().getParameterMap()));
        try {
            UserCoupon userCoupon = UserCoupon.toBean(userCouponEncryptStr);
            userCoupon.setUserId(userId);
            userCoupon.setStatus(0);
            userCoupon.setValidDate(userCouponService.getValidDate(userCoupon.getCouponId()));
            userCoupon.setCreateTime(new Date());
            userCoupon.setUpdateTime(new Date());
            userCouponService.insert(userCoupon);
            return ResultMapUtil.genDefaultSuccessDataMap("保存成功");
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                return ResultMapUtil.genErrorMap("该停车券已被用户领取。");
            }

            e.printStackTrace();
            return ResultMapUtil.genErrorMap("新增失败");
        }
    }

    @RequestMapping("page/myCouponListIndex")
    public ModelAndView myCouponListIndex(Integer userId) throws Exception {
        LogUtils.debug(JSONObject.toJSONString(getRequest().getParameterMap()));
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/coupon/myCouponList");

        UserCoupon userCoupon = new UserCoupon();
        userCoupon.setUserId(userId);
        userCoupon.setStatus(1);
        List<UserCoupon> usedCoupons = userCouponService.findCascade(userCoupon);
        mv.addObject("usedCoupons", usedCoupons);

        userCoupon.setStatus(0);
        userCoupon.setExpireDate(new Date());
        List<UserCoupon> expiredCoupons = userCouponService.findCascade(userCoupon);
        mv.addObject("expiredCoupons", expiredCoupons);

        userCoupon.setStatus(0);
        userCoupon.setExpireDate(null);
        userCoupon.setValidDate(new Date());
        List<UserCoupon> unUsedCoupons = userCouponService.findCascade(userCoupon);
        mv.addObject("unUsedCoupons", unUsedCoupons);

        return mv;
    }


}
